import axios from 'axios';
import { Message } from 'element-ui';

// 创建axios实例
const $http = axios.create({
  baseURL: '/materials',
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
});
// request拦截器
$http.interceptors.request.use(
  (config) => {
    const tokenSign = sessionStorage.getItem('tokenSign');
    if (tokenSign) {
      config.headers['Authorization'] = tokenSign;
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
$http.interceptors.response.use(
  (res) => {
    const code = res.data.code;
    if (code && code !== 0) {
      Message({
        message: res.data.message,
        type: 'error',
        duration: 3 * 1000,
      });
      return Promise.reject(res.data);
    } else {
      return res.data.data;
    }
  },
  (error) => {
    console.log('err' + error);
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000,
    });
    return Promise.reject(error);
  }
);

export default $http;
